"""
检查并删除没有图片的景点
"""
from django.core.management.base import BaseCommand
from apps.attractions.models import Attraction


class Command(BaseCommand):
    help = '检查并删除没有图片的景点'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='只显示将要删除的景点，不实际删除',
        )

    def handle(self, *args, **options):
        self.stdout.write('检查没有图片的景点...')

        # 查找没有图片的景点
        no_images = Attraction.objects.filter(
            amap_image_urls__isnull=True
        ) | Attraction.objects.filter(amap_image_urls=[])

        # 也检查本地图片
        no_local_images = Attraction.objects.filter(
            amap_image_urls__isnull=True
        ).filter(
            amap_image_urls=[]
        ).exclude(images__isnull=False)

        total_no_images = no_images.count()
        self.stdout.write(f'找到 {total_no_images} 个没有高德地图图片的景点')

        if total_no_images > 0:
            self.stdout.write('\n没有图片的景点列表:')
            for i, attr in enumerate(no_images, 1):
                self.stdout.write(f'{i}. {attr.name} (ID: {attr.id}, POI: {attr.amap_poi_id})')

        # 统计数据
        total = Attraction.objects.count()
        with_images = total - total_no_images

        self.stdout.write(f'\n数据统计:')
        self.stdout.write(f'总景点数: {total}')
        self.stdout.write(f'有图片的景点: {with_images}')
        self.stdout.write(f'没有图片的景点: {total_no_images}')

        # 执行删除
        if total_no_images > 0:
            if options['dry_run']:
                self.stdout.write('\n--- 这是预览模式，不会实际删除 ---')
                self.stdout.write(f'将要删除 {total_no_images} 个景点')
            else:
                confirm = input(f'\n确认删除 {total_no_images} 个没有图片的景点? (y/N): ')
                if confirm.lower() in ['y', 'yes']:
                    deleted_count, _ = no_images.delete()
                    self.stdout.write(
                        self.style.SUCCESS(f'成功删除 {deleted_count} 个景点')
                    )

                    # 显示剩余数据统计
                    remaining = Attraction.objects.count()
                    self.stdout.write(f'剩余景点数: {remaining}')
                else:
                    self.stdout.write('取消删除操作')
        else:
            self.stdout.write(self.style.SUCCESS('所有景点都有图片，无需删除'))
